﻿<h1>Interfaces in Go</h1>

<p>
Interface types are one special kind of types in Go.
Interface kind plays several important roles in Go.
Firstly, interface types make Go support value boxing.
Consequently, through value boxing, reflection and polymorphism get supported.
</p>

<p>
The remaining of this article will explain the functionalities of interfaces
in detail. Some interface related details will also be shown.
</p>

<h3>What Are Interface Types?</h3>

<p>
An interface type specifies a collection of
<a href="method.html#method-set">method prototypes</a>.
In other words, each interface type defines a <a href="method.html#method-set">method set</a>.
In fact, we can view an interface type as a method set.
For any of the method prototype specified in an interface type,
its name can't be the blank identifier <code>_</code>.
</p>

<p>
We also often say that each interface type specifies a behavior set (represented by the method set specified by that interface type).
</p>

<div>
Some examples of interface types:
<pre class="line-numbers"><code class="language-go">// This is a non-defined interface type.
interface {
	About() string
}

// ReadWriter is a defined interface type.
type ReadWriter interface {
	Read(buf []byte) (n int, err error)
	Write(buf []byte) (n int, err error)
}

// Runnable is an alias of a non-defined interface type.
type Runnable = interface {
	Run()
}
</code></pre>

<p>
</p>

Please note that the <code>error</code> result type in the method prototypes
specified by the <code>ReadWriter</code> interface type is
<a href="https://golang.org/pkg/builtin/#error">a built-in interface type</a>.
It is defined as

<pre class="line-numbers"><code class="language-go">type error interface {
        Error() string
}
</code></pre>

<p>
</p>

In particular, an interface type without specifying any method prototype
is called a blank interface type.
Here are some blank interface types examples:

<pre class="line-numbers"><code class="language-go">// A non-defined blank interface type.
interface{}

// Type I is a defined blank interface type.
type I interface{}
</code></pre>
</div>

<h3>The Method Set of a Type</h3>

<div>
Each type has a <a href="method.html#method-set">method set</a> associated with it.
<ul>
<li>
	For a non-interface type, its method set is the prototype collection of
	all <a href="method.html">the methods (either explicit or implicit ones) declared</a> for it.
</li>
<li>
	For an interface type, its method set is the method prototype collection it specifies.
</li>
</ul>
</div>

<p>
For convenience, the method set of a type is often also called
the method set of any value of the type.
</p>

<p>
Two non-defined interface types are identical if their method sets are identical.
Please note, non-exported method names, which start with lower-case letters,
from different packages will be always viewed as two different method names,
even if the two method names are the same in literal.
</p>

<a class="anchor" id="implementation"></a>
<h3>What Are Implementations?</h3>

<p>
If the method set of an arbitrary type <code>T</code>, <code>T</code>
may be an interface type or not,
is a super set of the method set of an interface type <code>I</code>,
then we say type <code>T</code> implements interface <code>I</code>.
</p>

<p>
Implementations are all implicit in Go.
The implementation relations are not needed to be specified for compilers in code explicitly.
There is not an <code>implements</code> keyword in Go.
Go compilers will check the implementation relations automatically as needed.
</p>

<p>
An interface type always implements itself.
Two interface types with the same method set implement each other.
</p>

<div>
For example, in the following example, the method sets of
struct pointer type <code>*Book</code>, integer type <code>MyInt</code> and
pointer type <code>*MyInt</code> all contain the method prototype
<code>About() string</code>, so they all implement the above mentioned
interface type <code>interface {About() string}</code>.
<pre class="line-numbers"><code class="language-go">type Book struct {
	name string
	// more other fields ...
}

func (book *Book) About() string {
	return "Book: " + book.name
}

type MyInt int

func (MyInt) About() string {
	return "I'm a custom integer value"
}
</code></pre>

<p>
</p>

<p>
Note, as any method set is a super set of a blank method set,
so <b>any type implements any blank interface type</b>.
This is an important fact in Go.
</p>

The implicit implementation design makes it possible to let concrete types
defined in other library packages, such as standard packages,
passively implement some interface types declared in user packages.
For example, if we declare an interface type as the following one,
then the type <code>DB</code> and type <code>Tx</code> declared in
<a href="https://golang.org/pkg/database/sql/">the <code>database/sql</code>
standard package</a> will both implement the interface type automatically,
for they both have the three corresponding methods specified in the interface.

<pre class="line-numbers"><code class="language-go">import "database/sql"

...

type DatabaseStorer interface {
	Exec(query string, args ...interface{}) (sql.Result, error)
	Prepare(query string) (*sql.Stmt, error)
	Query(query string, args ...interface{}) (*sql.Rows, error)
}
</code></pre>
</div>

<a class="anchor" id="boxing"></a>
<h3>Value Boxing</h3>

<div>
<p>
We can view each interface value as a box to encapsulate a non-interface value.
To box/encapsulate a non-interface value into an interface value,
the type of the non-interface value must implement the type of the interface value.
</p>

In Go, if a type <code>T</code> implements an interface type <code>I</code>,
then any value of type <code>T</code> can be implicitly converted to type <code>I</code>.
In other words, any value of type <code>T</code> is
<a href="constants-and-variables.html#assignment">assignable</a>
to (modifiable) values of type <code>I</code>.
When a <code>T</code> value is converted (assigned) to an <code>I</code> value,
<ul>
<li>
	if type <code>T</code> is a non-interface type, then
	a copy of the <code>T</code> value is boxed (or encapsulated)
	into the result (or destination) <code>I</code> value.
	The time complexity of the copy is <code><i>O</i>(n)</code>,
	where <code>n</code> is the size of copied <code>T</code> value.
</li>
<li>
	if type <code>T</code> is also an interface type, then
	a copy of the value boxed in the <code>T</code> value is boxed
	(or encapsulated) into the result (or destination) <code>I</code> value.
	The standard Go compiler makes an optimization here,
	so the time complexity of the copy is <code><i>O</i>(1)</code>,
	instead of <code><i>O</i>(n)</code>.
	<!--
	http://commaok.xyz/post/interface-allocs
	since Go1.5, in the official compiler implementation (), if the dynamic value
	is not a pointer, the runtime will alloc memory for a copy of the dynamic value and
	storage the pointers of the copy in the interface value.
	-->
</li>
</ul>

<p>
The type information of the boxed value is also stored in the result (or destination) interface value.
(This will be further explained below.)
</p>

<p>
When a value is boxed in an interface value, the value is called
the <b><i>dynamic value</i></b> of the interface value.
The type of the dynamic value is called the
<b><i>dynamic type</i></b> of the interface value.
</p>

<p>
The direct part of the dynamic value of an interface value is immutable,
though we can replace the dynamic value of an interface value with another dynamic value.
</p>

<!--
<p>
The <a href="type-system-overview.html#concrete-type">concrete value/type</a> of an interface value is its dynamic value/type.
</p>
-->

<p>
In Go, the zero values of any interface type are represented
by the predeclared <code>nil</code> identifier.
Nothing is boxed in a nil interface value.
Assigning an untyped <code>nil</code> to an interface value will
clear the dynamic value boxed in the interface value.
</p>

<p><i>
(Note, the zero values of many non-interface types in Go
are also represented by <code>nil</code> in Go.
Non-interface nil values can also be boxed in interface values.
An interface value boxing a nil non-interface value still boxes something,
so it is not a nil interface value.)
</i></p>

<p>
As any type implements any blank interface types,
so any non-interface value can be boxed in (or assigned to) a blank interface value.
For this reason, blank interface types can be viewed as the
<code>any</code> type in many other languages.
</p>

<p>
When an untyped value (except untyped <code>nil</code> values)
is assigned to a blank interface value,
the untyped value will be first converted to its default type.
(In other words, we can think the untyped value is deduced as a value of its default type).
</p>

Let's view an example which demonstrates some assignments
with interface values as the destinations.

<pre class="line-numbers"><code class="language-go">package main

import "fmt"

type Aboutable interface {
	About() string
}

// Type *Book implements Aboutable.
type Book struct {
	name string
}
func (book *Book) About() string {
	return "Book: " + book.name
}

func main() {
	// A *Book value is boxed into an
	// interface value of type Aboutable.
	var a Aboutable = &Book{"Go 101"}
	fmt.Println(a) // &{Go 101}

	// i is a blank interface value.
	var i interface{} = &Book{"Rust 101"}
	fmt.Println(i) // &{Rust 101}

	// Aboutable implements interface{}.
	i = a
	fmt.Println(i) // &{Go 101}
}
</code></pre>

Please note, the prototype of the <code>fmt.Println</code> function used many times in previous articles is

<pre class="disable-line-numbers111"><code class="language-go">func Println(a ...interface{}) (n int, err error)
</code></pre>

<p>
This is why a <code>fmt.Println</code> function calls can take arguments of
any types.
</p>

The following is another example which shows how a blank interface value
is used to box values of any non-interface type.

<pre class="line-numbers"><code class="language-go">package main

import "fmt"

func main() {
	var i interface{}
	i = []int{1, 2, 3}
	fmt.Println(i) // [1 2 3]
	i = map[string]int{"Go": 2012}
	fmt.Println(i) // map[Go:2012]
	i = true
	fmt.Println(i) // true
	i = 1
	fmt.Println(i) // 1
	i = "abc"
	fmt.Println(i) // abc

	// Clear the boxed value in interface value i.
	i = nil
	fmt.Println(i) // &lt;nil&gt;
}
</code></pre>

<p>
</p>

<p>
Go compilers will build a global table which contains
the information of each type at compile time.
The information includes
what <a href="type-system-overview.html#type-kinds">kind</a> a type is,
what methods and fields a type owns,
what the element type of a container type is, type sizes, etc.
The global table will be loaded into memory when a program starts.
</p>

<p>
At run time, when a non-interface value is boxed into an interface value,
the Go runtime (at least for the standard Go runtime) will analyze and build
the implementation information for the type pair of the two values,
and store the implementation information in the interface value.
The implementation information for each non-interface type and interface type pair will only be
built most once and cached in a global map for execution efficiency consideration.
The number of entries of the global map never decreases.
In fact, a non-nil interface value just uses <a href="value-part.html#interface-structure">an internal pointer field
which references a cached implementation information entry</a>.
</p>

The implementation information for each (interface type, dynamic type) pair
includes two pieces of information:
<ol>
<li>
	the information of the dynamic type (a non-interface type)
</li>
<li>
	and a method table (a slice) which stores all the corresponding methods specified
	by the interface type and declared for the non-interface type (the dynamic type).
</li>
</ol>

The two pieces of information are essential for implementing two important features in Go.
<ol>
<li>
	The dynamic type information is the key to implement <a href="#reflection">reflection</a> in Go.
</li>
<li>
	The method table information is the key to implement polymorphism (polymorphism will be explained in the next section).
</li>
</ol>
</div>

<a class="anchor" id="polymorphism"></a>
<h3>Polymorphism</h3>

<p>
Polymorphism is one key functionality provided by interfaces,
and it is an important feature of Go.
</p>

<p>
When a non-interface value <code>t</code> of a type <code>T</code>
is boxed in an interface value <code>i</code> of type <code>I</code>,
calling a method specified by the interface type <code>I</code>
on the interface value <code>i</code>
will call the corresponding method declared for the non-interface type <code>T</code>
on the non-interface value <code>t</code> actually.
In other words, <b>calling the method of an interface value will
call the corresponding method of the dynamic value of the interface value actually</b>.
For example, calling method <code>i.m</code> will call method <code>t.m</code> actually.
With different dynamic values of different dynamic types boxed into the interface value,
the interface value behaves differently. This is called polymorphism.
</p>

<p>
When method <code>i.m</code> is called, the method table in the implementation information
stored in <code>i</code> will be looked up to find and call the corresponding method <code>t.m</code>.
The method table is a slice and the lookup is just a slice element indexing, so no much time is consumed.
</p>

<p><i>
(Note, calling methods on a nil interface value will panic at run time,
for there are no available declared methods can be called.)
</i></p>

<div>
An example:
<pre class="line-numbers"><code class="language-go">package main

import "fmt"

type Filter interface {
	About() string
	Process([]int) []int
}

// UniqueFilter is used to remove duplicate numbers.
type UniqueFilter struct{}
func (UniqueFilter) About() string {
	return "remove duplicate numbers"
}
func (UniqueFilter) Process(inputs []int) []int {
	outs := make([]int, 0, len(inputs))
	pusheds := make(map[int]bool)
	for _, n := range inputs {
		if !pusheds[n] {
			pusheds[n] = true
			outs = append(outs, n)
		}
	}
	return outs
}

// MultipleFilter is used to keep only
// the numbers which are multiples of
// the MultipleFilter as an int value.
type MultipleFilter int
func (mf MultipleFilter) About() string {
	return fmt.Sprintf("keep multiples of %v", mf)
}
func (mf MultipleFilter) Process(inputs []int) []int {
	var outs = make([]int, 0, len(inputs))
	for _, n := range inputs {
		if n % int(mf) == 0 {
			outs = append(outs, n)
		}
	}
	return outs
}

// With the help of polymorphism, only one
// "filterAndPrint" function is needed.
func filterAndPrint(fltr Filter, unfiltered []int) []int {
	// Call the methods of "fltr" will call the
	// methods of the value boxed in "fltr" actually.
	filtered := fltr.Process(unfiltered)
	fmt.Println(fltr.About() + ":\n\t", filtered)
	return filtered
}

func main() {
	numbers := []int{12, 7, 21, 12, 12, 26, 25, 21, 30}
	fmt.Println("before filtering:\n\t", numbers)

	// Three non-interface values are boxed into
	// three Filter interface slice element values.
	filters := []Filter{
		UniqueFilter{},
		MultipleFilter(2),
		MultipleFilter(3),
	}

	// Each slice element will be assigned to the
	// local variable "fltr" (of interface type
	// Filter) one by one. The value boxed in each
	// element will also be copied into "fltr".
	for _, fltr := range filters {
		numbers = filterAndPrint(fltr, numbers)
	}
}
</code></pre>

The output:
<pre class="output"><code>before filtering:
	 [12 7 21 12 12 26 25 21 30]
remove duplicate numbers:
	 [12 7 21 26 25 30]
keep multiples of 2:
	 [12 26 30]
keep multiples of 3:
	 [12 30]
</code></pre>

<p>
In the above example, polymorphism makes it unnecessary to
write one <code>filterAndPrint</code> function for each filter types.
</p>

<p>
Besides the above benefit, polymorphism also makes it possible for the developers
of a library code package to declare an exported interface type and declare a function (or method)
which has a parameter of the interface type, so that a user of the package
can declare a type, which implements the interface type, in user code and
pass arguments of the user type to calls to the function (or method).
The developers of the code package don't need to care about how the user type is declared,
as long as the user type satisfies the behaviors specified
by the interface type declared in the library code package.
</p>
</div>

<p>
In fact, polymorphism is not an essential feature for a language.
There are alternative ways to achieve the same job, such as callback functions.
But the polymorphism way is cleaner and more elegant.
</p>

<a class="anchor" id="reflection"></a>
<h3>Reflection</h3>

<p>
The dynamic type information stored in an interface value
can be used to inspect the dynamic value of the interface value
and manipulate the values referenced by the dynamic value.
This is called reflection in programming.
</p>

<p>
Currently (Go 1.13), Go doesn't support generic for custom functions and types.
Reflection partially remedies the inconveniences caused by the lack of generics.
</p>

<p>
This article will not explain the functionalities provided by
<a href="https://golang.org/pkg/reflect/">the <code>reflect</code> standard package</a>.
Please read <a href="reflection.html">reflections in Go</a>
to get how to use this package.
Below will only introduce the built-in reflection functionalities in Go.
In Go, built-in reflections are achieved with type assertions and <code>type-switch</code> control flow code blocks.
</p>

<a class="anchor" id="type-assertion"></a>
<h4>Type assertion</h4>

<div>
There are four kinds of interface value involved value conversion cases in Go:
<ol>
<li>
	convert a non-interface value to an interface value,
	where the type of the non-interface value
	must implement the type of the interface value.
</li>
<li>
	convert an interface value to an interface value,
	where the type of the source interface value
	must implement the type of the destination interface value.
</li>
<li>
	convert an interface value to a non-interface value,
	where the type of the non-interface value
	must implement the type of the interface value.
</li>
<li>
	convert an interface value to an interface value,
	where the type of the source interface value
	may or may not implement the type of the destination interface value.
</li>
</ol>

<p>
Above has explained the first two kinds of cases.
The two both require the source value type must implement the destination interface type.
The convertibility for the first two are verified at compile time.
</p>

<p>
Here will explain the later two kinds of cases.
The convertibility for the later two are verified at run time,
by using a syntax called <b><i>type assertion</i></b>.
In fact, the syntax also applies to the second kind of conversions.
</p>

The form of a type assertion expression is <code>i.(T)</code>,
where <code>i</code> is an interface value and <code>T</code>
is a type name or a type literal.
Type <code>T</code> must be
<ul>
<li>
	either an arbitrary non-interface type,
</li>
<li>
	or an arbitrary interface type.
</li>
</ul>

In a type assertion <code>i.(T)</code>,
<code>i</code> is called the asserted value
and <code>T</code> is called the asserted type.
A type assertion might succeed or fail.
<ul>
<li>
	In case of <code>T</code> is a non-interface type,
	if the dynamic type of <code>i</code> exists and is identical to <code>T</code>, then the assertion will succeed,
	otherwise, the assertion will fail.
	When the assertion succeeds, the evaluation result of the assertion is a copy of the dynamic value of <code>i</code>.
	We can view assertions of this case as value unboxing attempt.
</li>
<li>
	In case of <code>T</code> is an interface type,
	if the dynamic type of the <code>i</code> exists and implements <code>T</code>,
	then the assertion will succeed, otherwise, the assertion will fail.
	When the assertion succeeds, a copy of the dynamic value of <code>i</code> will be boxed into a <code>T</code> value
	and the <code>T</code> value will be used as the evaluation result of the assertion.
</li>
</ul>

<p>
When a type assertion fails, its evaluation result is a zero value of the asserted type.
</p>

<p>
By the rules described above, if the asserted value in a type assertion
is a nil interface value, then the assertion will always fail.
</p>

<p>
For most scenarios, a type assertion is used as a single-value expression.
However, when a type assertion is used as the only source value expression
in an assignment, it can result in a second optional untyped boolean value
and be viewed as a multi-value expression.
The second optional untyped boolean value indicates whether or not the type assertion succeeds.
</p>

<p>
Note, if a type assertion fails and the type assertion is used as a
single-value expression (the second optional bool result is absent),
then a panic will occur.
</p>

An example which shows how to use type assertions (asserted types are non-interface types):
<pre class="line-numbers"><code class="language-go">package main

import "fmt"

func main() {
	// Compiler will deduce the type of 123 as int.
	var x interface{} = 123

	// Case 1:
	n, ok := x.(int)
	fmt.Println(n, ok) // 123 true
	n = x.(int)
	fmt.Println(n) // 123

	// Case 2:
	a, ok := x.(float64)
	fmt.Println(a, ok) // 0 false

	// Case 3:
	a = x.(float64) // will panic
}
</code></pre>

<p>
</p>

Another example which shows how to use type assertions (asserted types are interface types):
<pre class="line-numbers"><code class="language-go">package main

import "fmt"

type Writer interface {
	Write(buf []byte) (int, error)
}

type DummyWriter struct{}
func (DummyWriter) Write(buf []byte) (int, error) {
	return len(buf), nil
}

func main() {
	var x interface{} = DummyWriter{}
	var y interface{} = "abc"
	// Now the dynamic type of y is "string".
	var w Writer
	var ok bool

	// Type DummyWriter implements both
	// Writer and interface{}.
	w, ok = x.(Writer)
	fmt.Println(w, ok) // {} true
	x, ok = w.(interface{})
	fmt.Println(x, ok) // {} true

	// The dynamic type of y is "string",
	// which doesn't implement Writer.
	w, ok = y.(Writer)
	fmt.Println(w, ok) // &lt;nil&gt; false
	w = y.(Writer)     // will panic
}
</code></pre>

<p>
</p>

<p>
In fact, for an interface value <code>i</code> with dynamic type as <code>T</code>,
the method call <code>i.m(...)</code> is equivalent to the method call <code>i.(T).m(...)</code>.
</p>
</div>

<div>
</div>

<a class="anchor" id="type-switch"></a>
<h4><code>type-switch</code> control flow block</h4>

<div>

The <code>type-switch</code> code block syntax may be the weirdest syntax in Go.
It can be viewed as the enhanced version of type assertion.
A <code>type-switch</code> code block is some similar with a <code>switch-case</code> control flow code block.
It looks like:
<pre class="line-numbers"><code class="language-go">switch aSimpleStatement; v := x.(type) {
case TypeA:
	...
case TypeB, TypeC:
	...
case nil:
	...
default:
	...
}
</code></pre>

<p>
The <code>aSimpleStatement;</code> portion is optional in a <code>type-switch</code> code block.
<code>aSimpleStatement</code>must be a <a href="expressions-and-statements.html#simple-statements">simple statement</a>.
<code>x</code> must be an interface value and it is called the asserted value.
<code>v</code> is called the assertion result, it must be present in a short variable declaration form.
</p>

<p>
Each <code>case</code> keyword in a <code>type-switch</code> block can be followed by
a <code>nil</code> identifier and several type names or type literals.
None of such items can be duplicate in the same <code>type-switch</code> code block.
</p>

<p>
If the type denoted by a type name or type literal following a <code>case</code> keyword
in a <code>type-switch</code> code block is not an interface type, then it
must implement the interface type of the asserted value.
</p>

Here is an example in which a <code>type-switch</code> control flow code block is used.
<pre class="line-numbers"><code class="language-go">package main

import "fmt"

func main() {
	values := []interface{}{
		456, "abc", true, 0.33, int32(789),
		[]int{1, 2, 3}, map[int]bool{}, nil,
	}
	for _, x := range values {
		// Here, v is declared once, but it denotes
		// different variables in different branches.
		switch v := x.(type) {
		case []int: // a type literal
			// The type of v is "[]int" in this branch.
			fmt.Println("int slice:", v)
		case string: // one type name
			// The type of v is "string" in this branch.
			fmt.Println("string:", v)
		case int, float64, int32: // multiple type names
			// The type of v is "interface{}",
			// the same as x in this branch.
			fmt.Println("number:", v)
		case nil:
			// The type of v is "interface{}",
			// the same as x in this branch.
			fmt.Println(v)
		default:
			// The type of v is "interface{}",
			// the same as x in this branch.
			fmt.Println("others:", v)
		}
		// Note, each variable denoted by v in the
		// last three branches is a copy of x.
	}
}
</code></pre>

The output:
<pre class="output"><code>number: 456
string: abc
others: true
number: 0.33
number: 789
int slice: [1 2 3]
others: map[]
&lt;nil&gt;
</code></pre>

<p>
</p>

The above example is equivalent to the following in logic:
<pre class="line-numbers"><code class="language-go">package main

import "fmt"

func main() {
	values := []interface{}{
		456, "abc", true, 0.33, int32(789),
		[]int{1, 2, 3}, map[int]bool{}, nil,
	}
	for _, x := range values {
		if v, ok := x.([]int); ok {
			fmt.Println("int slice:", v)
		} else if v, ok := x.(string); ok {
			fmt.Println("string:", v)
		} else if x == nil {
			v := x
			fmt.Println(v)
		} else {
			_, isInt := x.(int)
			_, isFloat64 := x.(float64)
			_, isInt32 := x.(int32)
			if isInt || isFloat64 || isInt32 {
				v := x
				fmt.Println("number:", v)
			} else {
				v := x
				fmt.Println("others:", v)
			}
		}
	}
}
</code></pre>

<p>
</p>

<code>type-switch</code> code blocks are similar with <code>switch-case</code> code blocks in some aspects.
<ul>
<li>
	Like <code>switch-case</code> blocks, in a <code>type-switch</code> code block,
	there can be most one <code>default</code> branch.
</li>
<li>
	Like <code>switch-case</code> blocks, in a <code>type-switch</code> code block,
	if the <code>default</code> branch is present,
	it can be the last branch, the first branch, or a middle branch.
</li>
<li>
	Like <code>switch-case</code> blocks, a <code>type-switch</code> code block may not contain any branches,
	it will be viewed as a no-op.
</li>
</ul>

<p>
But, unlike <code>switch-case</code> code blocks, <code>fallthrough</code> statements
can't be used within branch blocks of a <code>type-switch</code> code block.
</p>

</div>

<h3>More About Interfaces in Go</h3>

<a class="anchor" id="embedding"></a>
<h4>Interface type embedding</h4>

<div>
An interface type can embed a type name which denotes another interface type.
The final effect is the same as unfolding the method prototypes
specified by the embedded interface type into the definition body
of the embedding interface type.
For example, in the following example, the respective method sets
specified by interface types <code>Ic</code>, <code>Id</code> and <code>Ie</code>
are identical.

<pre class="line-numbers"><code class="language-go">type Ia interface {
	fa()
}

type Ib = interface {
	fb()
}

type Ic interface {
	fa()
	fb()
}

type Id = interface {
	Ia // embed Ia
	Ib // embed Ib
}

type Ie interface {
	Ia // embed Ia
	fb()
}
</code></pre>

<p>
</p>

Up to now (Go 1.13), two interface types can't embed each other
if they both specify a method prototype with the same name,
and they also can't be embeded at the same time in the same third interface type,
even if the two method prototypes are identical.
For example, the following assumed interface types are all illegal.

<pre class="line-numbers"><code class="language-go">type Ix interface {
	Ia
	Ic
}

type Iy = interface {
	Ib
	Ic
}

type Iz interface {
	Ic
	fa()
}
</code></pre>

<p>
The limit demonstrated in the above example might <a href="https://github.com/golang/proposal/blob/master/design/6977-overlapping-interfaces.md">be removed in later Go versions</a>.
</p>

<p>
An interface type can't embed itself or any other interface types that embeds the interface type, recursively.
</p>
</div>

<a class="anchor" id="comparison"></a>
<h4>Interface values involved comparisons</h4>

<div>
There are two cases of interface values involved comparisons:
<ol>
<li>
	comparisons between a non-interface value and an interface value.
</li>
<li>
	comparisons between two interface values.
</li>
</ol>

<p>
For the first case,
the type of the non-interface value must implement the type
(assume it is <code>I</code>) of the interface value,
so the non-interface value can be converted to (boxed into)
an interface value of <code>I</code>.
This means a comparison between a non-interface value and an interface value
can be translated to a comparison between two interface values.
So below only comparisons between two interface values will be explained.
</p>

<p>
Comparing two interface values is comparing their respective dynamic types
and dynamic values actually.
</p>

The steps of comparing two interface values (with the <code>==</code> operator):
<ol>
<li>
	if one of the two interface values is a nil interface value,
	then the comparison result is whether or not
	the other interface value is also a nil interface value.
</li>
<li>
	if the dynamic types of the two interface values are two different types,
	then the comparison result is <code>false</code>.
</li>
<li>
	for the case of the dynamic types of the two interface values are the same type,
	<ul>
	<li>
		if the same dynamic type is an
		<a href="value-conversions-assignments-and-comparisons.html#comparison-rules">incomparable type</a>,
		a panic will occur.
	</li>
	<li>
		otherwise, the comparison result is the result of comparing the dynamic values of the two interface values.
	</li>
	</ul>
</li>
</ol>

In short, two interface values are equal only if one of the following conditions is satisfied.
<ol>
<li>
	They are both nil interface values.
</li>
<li>
	Their dynamic types are identical and comparable, and their dynamic values are equal to each other.
</li>
</ol>


By the rules, two interface values which dynamic values are both <code>nil</code>
may be not equal. An example:
<pre class="line-numbers"><code class="language-go">package main

import "fmt"

func main() {
	var a, b, c interface{} = "abc", 123, "a"+"b"+"c"
	// A case of step 2.
	fmt.Println(a == b) // false
	// A case of step 3.
	fmt.Println(a == c) // true

	var x *int = nil
	var y *bool = nil
	var ix, iy interface{} = x, y
	var i interface{} = nil
	// A case of step 2.
	fmt.Println(ix == iy) // false
	// A case of step 1.
	fmt.Println(ix == i) // false
	// A case of step 1.
	fmt.Println(iy == i) // false

	// []int is an incomparable type
	var s []int = nil
	i = s
	// A case of step 1.
	fmt.Println(i == nil) // false
	// A case of step 3.
	fmt.Println(i == i) // will panic
}
</code></pre>
</div>

<h4>The internal structure of interface values</h4>

<p>
For the official Go compiler/runtime, blank interface values and non-blank interface values
are represented with two different internal structures.
Please read <a href="value-part.html#interface-structure">value parts</a> for details.
</p>

<!--
todo: need a picture. Three parts
* the interface value layout
* the implementation info layout
* the type info layout
-->

<h4>Pointer dynamic value vs. non-pointer dynamic value</h4>

<p>
The official Go compiler/runtime makes an optimization
which makes that boxing pointer values into interface values
is more efficient than boxing non-pointer values.
For <a href="value-copy-cost.html">small size values</a>,
the efficiency differences are small,
but for large size values, the differences may be not small.
For the same optimization, type assertions with a pointer type
are also more efficient than type assertions with the base type
of the pointer type if the base type is a large size type.
</p>

<p>
So please try to avoid boxing large size values, box their pointers instead.
</p>

<h4>Values of <code>[]T</code> can't be directly converted to <code>[]I</code>,
	even if type <code>T</code> implements interface type <code>I</code>.</h4>

<div>
For example, sometimes, we may need to convert a <code>[]string</code> value
to <code>[]interface{}</code> type. Unlike some other languages, there is no
direct ways to make the conversion. We must make the conversion manually in a loop:
<pre class="line-numbers"><code class="language-go">package main

import "fmt"

func main() {
	words := []string{
		"Go", "is", "a", "high",
		"efficient", "language.",
	}

	// The prototype of fmt.Println function is
	// func Println(a ...interface{}) (n int, err error).
	// So words... can't be passed to it as the argument.

	// fmt.Println(words...) // not compile

	// Convert the []string value to []interface{}.
	iw := make([]interface{}, 0, len(words))
	for _, w := range words {
		iw = append(iw, w)
	}
	fmt.Println(iw...) // compiles okay
}
</code></pre>
</div>

<h4>Each method specified in an interface type corresponds to an implicit function</h4>

<div>

<p>
For each method with name <code>m</code>
in the method set defined by an interface type <code>I</code>,
compilers will implicitly declare a function named <code>I.m</code>,
which has one more input parameter, of type <code>I</code>, than method <code>m</code>.
The extra parameter is the first input parameter of function <code>I.m</code>.
Assume <code>i</code> is an interface value of <code>I</code>,
then the method call <code>i.m(...)</code> is equivalent to the function call <code>I.m(i, ...)</code>.
</p>

An example:
<pre class="line-numbers"><code class="language-go">package main

import "fmt"

type I interface {
	m(int)bool
}

type T string
func (t T) m(n int) bool {
	return len(t) > n
}

func main() {
	var i I = T("gopher")
	fmt.Println(i.m(5))                        // true
	fmt.Println(I.m(i, 5))                     // true
	fmt.Println(interface{m(int)bool}.m(i, 5)) // true

	// The following lines compile okay,
	// but will panic at run time.
	I(nil).m(5)
	I.m(nil, 5)
	interface {m(int) bool}.m(nil, 5)
}
</code></pre>
</div>
